﻿/*
培训任务的添加修改
*/
//
angular.module('trainingTaskPreview', ['loadModule','Common','statisticService','filepreview'])
// 设置焦点 标签用
.directive('setFocus', function () {
     return function (scope, element) {
         element[0].focus();
     };
 })
 .directive("trainingTaskPreview", ["$timeout", "Msg","requestStatisticService", 'RequestTrainService',"sysUserInfo", function ($timeout, Msg,RSS,ST,sysUserInfo) {
     return {
        restrice: "AE",
        scope: {             
             taskObj: "=",   // 培训计划对象
             onClose: "&",    //关闭窗口            
             showKnow:"=",//是否需要题库        
        },
        templateUrl: "/system/directive/train/trainingtask/training_task_preview.html",
        link: function (scope, element, attr) {
            

            //课程  selectType=1普通课程，2共享课程
            scope.taskObjNew = angular.copy(scope.taskObj);

             //文件预览 
            scope.isFilePreview = { divhide: false, data: {} };
            // 文件预览
            scope.filePreview = function (item) {
                scope.isFilePreview.divhide = true;
                scope.isFilePreview.data = item;
            }

            // 初始化
            scope.init = function(){
                //任务的详情页还是  分类的
                //默认是任务
                scope.isTask=true;
                //报名状态(任务需要报名的时候才有用)
                scope.signUpState=0;//0初始 1审核中 2已通过 3失败
                if(scope.taskObjNew.isReviewed){
                    scope.warnMsg="注意：此任务需要学员报名参与并且管理员审核后才可开始学习！";
                    //查询是否报名
                     ST.getEnrollInfo({ xid: scope.taskObjNew.id, userid: sysUserInfo.getuserinfo().user_ID,xtype:1 }).then(function (response) {
                        if (response.errorcode == 0 && response.data != null && response.data != undefined && response.data != "") {
                           scope.signUpState=response.data.reviewed;
                           if(scope.signUpState==1){
                                scope.warnMsg="您的报名申请已提交，正在审核中，请耐心等待！";
                           }else if(scope.signUpState==2){
                                scope.warnMsg="您的报名申请已通过审核！";
                           }else if(scope.signUpState==3){
                                scope.warnMsg="您的报名申请未通过审核，详情请联系管理员！";
                           }
                        } 
                    });
                }
                


                //已完成的id
                scope.completeStr=-1;
                // loading
                scope.isRequestLoading = false;
                // 当前阶段
                scope.selStageFlag = 1;
                // 阶段课程列表
                scope.stageCourseList = [];
                //初始化课程的请求参数
                scope.courseParams = {
                    courseids: [],   //课程id
                    paperids: [], // 试卷id
                    upids: [],   //文件id
                    knowledgeids: [],    // 知识结构id
                    pageIndex: 1,
                    pageSize: 5
                }
                //汇总数据集合,为了排序 &&typeof(scope.taskObjNew.arragetype)=="string"
                if (scope.taskObjNew.hasOwnProperty('arragetype')){                   
//                    if(!Array.isArray(scope.taskObjNew.arragetype)){
//                        scope.taskObjNew.arragetype = JSON.parse(scope.taskObjNew.arragetype);
//                    } 
                    if(scope.taskObjNew.arrage!=undefined&&typeof(scope.taskObjNew.arrage)=="string"){
                        scope.taskObjNew.arrage=JSON.parse(scope.taskObjNew.arrage);
                    }
					if(scope.taskObjNew.arragetype!=undefined&&typeof(scope.taskObjNew.arragetype)=="string"){
                        scope.taskObjNew.arragetype=JSON.parse(scope.taskObjNew.arragetype);
                    }
                    scope.taskObjNew.arragetype.forEach(function(keyObj,index){
                        var totleList=[];
                         if (keyObj.hasOwnProperty('kssList')){ // 知识结构
                                keyObj.kssList.forEach(function(data,index){
                                    data.type=3;
                                    if(data.order==undefined||data.order==null||data.order==""){
                                        data.order=0;
                                    }
                                    totleList.push(data);
                                });
                        }
                        if (keyObj.hasOwnProperty('kseList')){ // 试卷
                                keyObj.kseList.forEach(function(data,index){
                                    data.type=2;
                                    if(data.order==undefined||data.order==null||data.order==""){
                                        data.order=0;
                                    }
                                    totleList.push(data);
                                });
                        }
                        if (keyObj.hasOwnProperty('kscList')){ //课程
                                keyObj.kscList.forEach(function(data,index){
                                    data.type=1;
                                    if(data.order==undefined||data.order==null||data.order==""){
                                        data.order=0;
                                    }
                                    totleList.push(data);
                                });
                        }
                        keyObj.totleList=totleList;
                        //强制任务学习才排序
                        if (scope.taskObjNew.arrage.isOrder!=undefined&&scope.taskObjNew.arrage.isOrder){
                            keyObj.totleList=keyObj.totleList.sort(function(obj1,obj2){
                              return obj1.order-obj2.order;
                            })
                        }
                    });
                   
                    //scope.selStage(scope.taskObjNew.arragetype[0],1);
                    scope.isTask=true;
                }else if(scope.taskObjNew.hasOwnProperty('knowledge_Id')){
                    scope.isTask=false;
                    if(scope.taskObjNew.know_select_course){
                        scope.selType(1);
                    }else if(scope.taskObjNew.know_select_exam){
                        scope.selectType=2;
                        scope.selType(2);
                    }else if(scope.taskObjNew.know_select_que){
                        scope.selectType=3;
                        scope.selType(3);
                    //订单过来的 不需要题库
                    //需要课程  和试卷
                    }else if(!scope.showKnow){
                        scope.selType(1);
                        scope.taskObjNew.know_select_course=true;
                        scope.taskObjNew.know_select_exam=true;
                        scope.taskObjNew.know_select_que=false;
                    }
                    
                }
                
                 //请求登录人对应的选中的任务 的任务进度   参数：arrangeId   userId
                ST.findOneProgress({ arrangeId: scope.taskObjNew.id, userId: sysUserInfo.getuserinfo().user_ID }).then(function (response) {
                    if (response.errorcode == 0 && response.data != null && response.data != undefined && response.data != "") {
                        if (response.data.json_details != null && response.data.json_details != "" && response.data.json_details != undefined) {
                            scope.completeStr = response.data.json_details;
                        } else {
                            scope.completeStr = "-1";
                        }

                    } else {
                        scope.completeStr = "-1";
                    }
                });

            }
            // 判断数组的属性是否存在
            scope.isTaskNotNull = function(list){
                if (!list.hasOwnProperty('kssList')) // 知识结构
                    list.kssList = [];
                if (!list.hasOwnProperty('kseList')) // 试卷
                    list.kseList = [];
                if (!list.hasOwnProperty('ksfList')) // 文件 
                    list.ksfList = [];
                if (!list.hasOwnProperty('kscList')) //课程
                    list.kscList = [];
                if (!list.hasOwnProperty('value')) //课程
                    list.value = "";
                return list;
            }
            //报名任务
            scope.signUpArrange=function(){
                ST.addEnrollInfo({ xid: scope.taskObjNew.id, userid: sysUserInfo.getuserinfo().user_ID, type: 1  }).then(function (response) {
                    if (response.errorcode == 0) {
                       Msg.warning("报名成功，请耐心等待管理员审核！")
                       scope.warnMsg="您的报名申请已提交，正在审核中，请耐心等待！";
                       scope.signUpState=1;
                     } else if (response.errorcode == 27) {
                            Msg.warning("报名任务不存在！")
                        } else if (response.errorcode == 28) {
                            Msg.warning("报名审核中，请耐心等待！")
                        } else if (response.errorcode == 29) {
                            Msg.warning("您已经报过名了，请不要重复操作！")
                        } else if (response.errorcode == 30) {
                            Msg.warning("您的报名审核失败，请联系管理员！")
                        }
                });
            }

            // 选中阶段
            scope.selStage = function(stageObj,ind){
                // 当前索引
                scope.selStageFlag = ind;                
            }
            
            // 随机试卷
            scope.getPaperUrl = function(paperUrl,coun){        
                scope.paperUrlList = paperUrl.split("/");
                scope.paperNum = scope.paperUrlList[scope.paperUrlList.length-1].split(".")[0];
                if(scope.paperNum != undefined && scope.paperNum != null && scope.paperNum != "" ){
                    scope.paperNum;
                    scope.paperReadNum = parseInt(Math.random() * coun+1);
                    scope.paperUrlList[scope.paperUrlList.length-1] = (scope.paperReadNum == 0)? "1.html": scope.paperReadNum+".html";
                    scope.paperUrl = scope.paperUrlList.join("/");
                } 
                if(scope.paperReadNum==0){
                    scope.paperReadNum=1;
                }   
                return scope.paperUrl ;
            }
            // 公共地址
            scope.commonUrl = ""; 
            // 页面跳转
            scope.openUrlLink = function (item,id) {
                //验证是否需要报名,
                if(scope.taskObjNew.isReviewed){
                    if(scope.signUpState==0){
                        Msg.warning("请先报名参与该任务！");
                        return;
                    }else if(scope.signUpState==1){
                        Msg.warning("报名审核中，请耐心等待！");
                        return;
                    }else if(scope.signUpState==3){
                        Msg.warning("报名审核失败，详情请联系管理员！");
                        return;
                    }
                }
                //验证是否强制学习（上一个是否学习完成）
                 if(scope.isTask){
                    var a=scope.validateTask(item);
                    if(!a){
                        return;
                    }
                }
                //这个指令只用于任务和班级预览
                if(id==undefined||id==null||id==""){
                    id="2";
                }
                //课程
                if (item.hasOwnProperty('course_Id')) {
                    if(item.hasOwnProperty("selectType")&&item.selectType==2&&!item.expire){
                        Msg.warning("该课程已过期，请联系管理员！");
                        return;
                    }
                    var url="";
                    //预览
                    if(commonFileUrl.indexOf("http")!=-1){
                         url = commonUrl + '/dispatcher/redirect?url=' + encodeURI(encodeURI(commonFileUrl + "/resources/template/" + item.course_Id + ".html?arrangeId=" + id + "&token=" + sysUserInfo.getuserinfotoken()));
                    }else{
                        url = commonUrl + '/dispatcher/redirect?url=' + encodeURI(encodeURI(window.location.protocol+commonFileUrl + "/resources/template/" + item.course_Id + ".html?arrangeId=" + id + "&token=" + sysUserInfo.getuserinfotoken()));
                    }
                    
                    // window.open(url);
                    scope.commonUrl=url;
                    $timeout(function () { document.getElementById("commonCHref").click(); }, 100);
                }  //课程
                else if (item.hasOwnProperty('courseId')) {
                    //预览
                    if(commonFileUrl.indexOf("http")!=-1){
                         url = commonUrl + '/dispatcher/redirect?url=' + encodeURI(encodeURI(commonFileUrl + "/resources/template/" + item.courseId + ".html?arrangeId=" + id + "&token=" + sysUserInfo.getuserinfotoken()));
                    }else{
                        url = commonUrl + '/dispatcher/redirect?url=' + encodeURI(encodeURI(window.location.protocol+commonFileUrl + "/resources/template/" + item.courseId + ".html?arrangeId=" + id + "&token=" + sysUserInfo.getuserinfotoken()));
                    }
                    // window.open(url);
                    scope.commonUrl=url;
                    $timeout(function () { document.getElementById("commonCHref").click(); }, 100);
                //试卷
                }else if (item.hasOwnProperty('paperId')) {
                    if (item.paper_Random == "0") {
                        item.url = scope.getPaperUrl(item.url, item.paperCount)
                    } else {
                        scope.paperReadNum = 0;
                    }
        //         scope.commonUrl =$rootScope.fileurl+item.url+"?arrangeId="+id+"&userid="+sysUserInfo.getuserinfo().user_ID+"&token="+sysUserInfo.getuserinfotoken()+"&date="+new Date();
                    scope.commonUrl = commonFileUrl + item.url + "?arrangeId=" + id + "&userid=" + sysUserInfo.getuserinfo().user_ID + "&token=" + sysUserInfo.getuserinfotoken() + "&random=" + (scope.paperReadNum == undefined ? 0 : scope.paperReadNum) + "&date=" + new Date();
                    //$timeout(function () { document.getElementById("commonCHref").click(); }, 50);
                    // 判断一下考试次数
                    if(item.examCount > 0){
                        ST.getExamNum({"paperid" : item.paperId,"userid" : sysUserInfo.getuserinfo().user_ID,"arrangId":id }).then(function(data){                    
                            if(item.examCount <= data.data){
                                Msg.warning("您的考试次数用完了");             
                                return;
                            }else{
                                $timeout(function () { document.getElementById("commonCHref").click(); }, 100);
                                // window.open(scope.commonUrl);
                            }
                        });
                    }else{
                        // window.open(scope.commonUrl);
                        $timeout(function () { document.getElementById("commonCHref").click(); }, 100);
                    }
                     
                //分类
                } else if (item.hasOwnProperty('knowledge_Id')) {
                    scope.commonUrl = "/member/index.html#/home/stuquelist/"+id+"/"+item.knowledge_Id+"/"+(item.know_select_que_type?item.know_select_que_type:0)+"/"+(item.know_select_que_num?item.know_select_que_num:0)+"/0/"+item.knowledge_Name+"/"+id+"/"+item.knowledge_Id+"/"+item.knowledge_Name+"/0///";
                   // $timeout(function(){document.getElementById("commonCHref").click();            },50);
                   $timeout(function () { document.getElementById("commonCHref").click(); }, 100);
                //    window.open(scope.commonUrl);
                } else {
                    Msg.warning("未识别类型！");
                    return;
                }

            }
           
           /****************************************************验证强制学校******************************************************/
           scope.validateTask=function(item){

           //编程思路
            //当前有培训任务集合与学习记录
            //1、先判断当前在学习，第几个阶段，如果不是第一个阶段，检查上一个阶段有没有学完
            //2、如果上一个阶段学完了，检查当前学习阶段内的课程，要学的课程排在第几，上一个课程是否学员
            var key = scope.taskObjNew.arragetype[scope.selStageFlag - 1].key; //当前是第几阶段，从2开始判读
            
            //强制学习
                if(scope.taskObjNew.arrage!=undefined&&scope.taskObjNew.arrage.isOrder){
					
					if (key > 1) {
						//强制学习
						if(scope.taskObjNew.arrage!=undefined&&scope.taskObjNew.arrage.isOrder){
							var shangjieduan = scope.taskObjNew.arragetype[key - 2];
							for (var i = 0; i < shangjieduan.kscList.length; i++) {
								var id = shangjieduan.kscList[i].course_Id;
								if (scope.completeStr.indexOf(id) == -1) {
									Msg.warning("提示", "您上一个阶段(" + shangjieduan.kscList[i].course_Name + ")还未完成噢！");
									return;
									break;
								}
							}
							for (var i = 0; i < shangjieduan.kseList.length; i++) {
								var id = shangjieduan.kseList[i].paperId;
								if (scope.completeStr.indexOf(id) == -1) {
									Msg.warning("提示", "您上一个阶段(" + shangjieduan.kseList[i].paperName + ")还未完成噢！");
									return;
									break;
								}
							}
							for (var i = 0; i < shangjieduan.kssList.length; i++) {
								var id = shangjieduan.kssList[i].knowledge_Id;
								if (scope.completeStr.indexOf(id) == -1) {
									 Msg.warning("提示","您上一个阶段还未完成噢！");
									return;
									break;
								}
							}
						}
					}
					
                    var preObj=null;
                    //匹配前一个课程
                    scope.taskObjNew.arragetype[scope.selStageFlag-1].totleList.forEach(function(data,index){
                        if(preObj==null){
                           //课程
                            if(item.type==1&&data.type==1){
                                if(data.course_Id==item.course_Id){
                                    if(index==0){
                                        preObj="0";
                                    }else{
                                        preObj=scope.taskObjNew.arragetype[scope.selStageFlag-1].totleList[index-1];
                                    }
                                }
                            //试卷
                            }else if(item.type==2&&data.type==2){
                                if(data.paperId==item.paperId){
                                    if(index==0){
                                        preObj="0";
                                    }else{
                                        preObj=scope.taskObjNew.arragetype[scope.selStageFlag-1].totleList[index-1];
                                    }
                                }
                            //知识分类
                            }else if(item.type==3&&data.type==3){
                                if(data.knowledge_Id==item.knowledge_Id){
                                    if(index==0){
                                        preObj="0";
                                    }else{
                                        preObj=scope.taskObjNew.arragetype[scope.selStageFlag-1].totleList[index-1];
                                    }
                                }
                            }
                        }
                    });

                     //课程
                    if(preObj.type==1){
                        if(scope.completeStr.indexOf(preObj.course_Id)==-1){
                            Msg.warning("提示","请先学习课程【"+preObj.course_Name+"】");
                            return false;
                        }else{
                            return true;
                        }
                    //试卷
                    }else if(preObj.type==2){
                        if(scope.completeStr.indexOf(preObj.paperId)==-1){
                            Msg.warning("提示","请先考核试卷【"+preObj.paperName+"】");
                            return false;
                        }else{
                            return true;
                        }
                    //知识分类
                    }else if(preObj.type==3){
                        if(scope.completeStr.indexOf(preObj.knowledge_Id)==-1){
                            Msg.warning("提示","请先学习大纲【"+preObj.knowledge_Name+"】");
                            return false;
                        }else{
                            return true;
                        }
                    }else{
                        return true;
                    }

                }else{
                    return true;
                }
           }
            //***************************************************知识分类开始*******************************************************************/
            scope.selectType=1;
            //课程试卷筛选 
            scope.selType=function(index){
                scope.selectType=index;
                if(index!=3){
                    if(index==1&&scope.taskObjNew.kscList!=undefined){
                        return;
                    }
                    if(index==2&&scope.taskObjNew.kseList!=undefined){
                        return;
                    }
                     //请求登录人对应的选中的任务 的任务进度   参数：arrangeId   userId
                    ST.findArrangeStage({ knowledgeids: scope.taskObjNew.knowledge_Id, state:index}).then(function (response) {
                        if (response.errorcode == 0) {
                            if(index==1){
                                scope.taskObjNew.kscList=response.datas;
                            }else{
                                scope.taskObjNew.kseList=response.datas;
                            }
                        } else {
                            scope.completeStr = "-1";
                        }
                    });
                }
            }
            //当前任务详细页改为知识分类也
            scope.openToDetail=function(obj){
                 //验证是否需要报名,
                if(scope.taskObjNew.isReviewed){
                    if(scope.signUpState==0){
                        Msg.warning("请先报名参与该任务！");
                        return;
                    }else if(scope.signUpState==1){
                        Msg.warning("报名审核中，请耐心等待！");
                        return;
                    }else if(scope.signUpState==3){
                        Msg.warning("报名审核失败，详情请联系管理员");
                        return;
                    }
                }
                var a=scope.validateTask(obj);
                if(!a){
                    return;
                }
                scope.taskObjNew=obj;
                scope.taskObjNew.id=scope.taskObj.id;
                scope.init();
            }
            //返回
            scope.backClose=function(){
                
                //判断返回的是哪儿
                if(scope.taskObj.hasOwnProperty('arragetype')&&!scope.taskObjNew.hasOwnProperty('arragetype')){
                    //是任务详细页跳转知识分类页
                    scope.taskObjNew=scope.taskObj;
                    scope.init();
                }else{
                    scope.onClose();
                }
            }
            //初始化之前判断有没有已过期的共享课程
            scope.beforeInit=function(){
                if(scope.taskObjNew.hasOwnProperty('arragetype')){
					if(scope.taskObjNew.arragetype!=undefined&&typeof(scope.taskObjNew.arragetype)=="string"){
                        scope.taskObjNew.arragetype=JSON.parse(scope.taskObjNew.arragetype);
                    }
                        var courseids="";
                       scope.taskObjNew.arragetype.forEach(function(arrageobj,index){
                            if(arrageobj.kscList.length>0){
                                    arrageobj.kscList.forEach(function(courseobj,cindex){
                                        if(courseobj.hasOwnProperty("selectType")&&courseobj.selectType==2){
                                            courseids+=(courseids.length>0?',':"")+courseobj.course_Id;
                                        }
                                    });
                            }
                      });
                     if(courseids.length>0){
                        ST.findExpireState({ xid: courseids, orgid:sysUserInfo.getuserinfo().organization_ID}).then(function (response) {
                            if (response.errorcode == 0) {
                                var hasids=response.datas.join(",");
                                scope.taskObjNew.arragetype.forEach(function(arrageobj,index){
                                        if(arrageobj.kscList.length>0){
                                                arrageobj.kscList.forEach(function(courseobj,cindex){
                                                    if(courseobj.hasOwnProperty("selectType")&&courseobj.selectType==2){
                                                        if(hasids.indexOf(courseobj.course_Id)!=-1){
                                                            courseobj.expire=true;
                                                        }else{
                                                            courseobj.expire=false;
                                                        }
                                                    }
                                                });
                                        }
                                });
                                
                            } else {
                                //请求失败
                            }
                            scope.init();
                        });
                    //无共享课程
                    }else{
                        scope.init();
                    }
                }else if(scope.taskObjNew.hasOwnProperty('knowledge_Id')){
                    scope.init();
                }
            }
            scope.beforeInit();
            //scope.init();
        }
    }
 } ]);
